<template>
	<view id="bookkeeping_container">
		<!-- Tab 栏 -->
		<view class="tabs">
			<view v-for="(tab, index) in tabs" 
				:key="index" 
				:class="['tab', { active: selectedTab === index }]"
				@click="selectTab(index)">
				{{ tab }}
			</view>
		</view>

		<!-- Tab内容区域 -->
		<view class="content">
			<view v-if="selectedTab === 0" class="content_view">
				<!-- 支出视图 -->
				<view class="expend_icon" 
					v-for="(item, index) of expendIcons" 
					:key="index"
					@click="switchCategory(item)"
					>
					<view class="expend_icon_img" :class="{'selected_category': selectedCategory == item.id}">
						<image :src="baseUrl + item.icon" mode="heightFix"></image>
					</view>
					<view class="expend_icon_text" :class="{'selected_category_t': selectedCategory == item.id}">
						{{ item.name }}
					</view>
				</view>
			</view>
			<view v-if="selectedTab === 1" class="content_view">
				<!-- 收入视图 -->
				<view class="expend_icon" 
					v-for="(item, index) of incomeIcons" 
					:key="index"
					@click="switchCategory(item)"
					>
					<view class="expend_icon_img" :class="{'selected_category': selectedCategory == item.id}">
						<image :src="baseUrl + item.icon" mode="heightFix"></image>
					</view>
					<view class="expend_icon_text" :class="{'selected_category_t': selectedCategory == item.id}">
						{{ item.name }}
					</view>
				</view>
			</view>
			<!-- 转账视图 -->
			<view v-if="selectedTab === 2">
				<view class="transfer_view">
					<!-- 转出账户 -->
					<view class="expend_account">
						<view class="expend_account_left" @click="showSelectAccout('expend')">
							<view class="expend_account_icon">
								<image src="../../static/bookkeeping/question.png" mode="heightFix"></image>
							</view>
							<view class="middle">
								-
							</view>
							<view class="expend_account_name">
								{{ expendAccount.name }}
								<span class="account_balance" v-if="expendAccount.name != '转出账户'">
									({{ expendAccount.balance }})
								</span>
							</view>
						</view>
						<view class="expend_account_right">
							<input type="text" class="right_inpt" v-model="transferValue">
						</view>
					</view>
					<!-- 互转图标 -->
					<view class="transfer_icon">
						<image src="../../static/bookkeeping/transfer.png" mode="heightFix"></image>
					</view>
					<!-- 转入账户 -->
					<view class="income_account">
						<view class="income_account_left" @click="showSelectAccout('income')">
							<view class="income_account_icon">
								<image src="../../static/bookkeeping/question.png" mode="heightFix"></image>
							</view>
							<view class="middle2">
								+
							</view>
							<view class="income_account_name">
								{{ incomeAccount.name }}
								<span class="account_balance" v-if="incomeAccount.name != '转入账户'">
									({{ incomeAccount.balance }})
								</span>
							</view>
						</view>
						<view class="income_account_right">
							<input type="text" class="right_inpt" v-model="transferValue">
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 账单选项 - 表单 -->
		<view class="bill_option" v-if="selectedTab != 2">
			<uni-forms :modelValue="billData" label-position="left" label-align="right">
				<!-- 类型选择 -->
				<uni-forms-item label="账本:" name="bookId" >
					<uni-data-select
					    v-model="billData.bookId"
					    :localdata="accountBookData"
						placeholder="选择账本"
					    >		
					</uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="账户:" name="accountId" >
					<uni-data-select
					    v-model="billData.accountId"
					    :localdata="assetAcountOption"
						placeholder="选择资产账户"
					    >		
					</uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="金额:" name="amount">
					<uni-easyinput type="digit" v-model="billData.amount" placeholder="请输入账单金额" />
				</uni-forms-item>
				<uni-forms-item label="备注:" name="remark">
					<uni-easyinput v-model="billData.remark" placeholder="请输入备注" />
				</uni-forms-item>
			</uni-forms>
		</view>
		
		<!-- 保存按钮 -->
		<view class="confirm_btn">
			<button
				type="default" 
				style="background-color: #efa31f; color: #fff;"
				@click="addBillHandle"
				>
				保存
			</button>
		</view>
		
		<!-- 弹出层：选择账户 -->
		<uni-popup ref="select_account" type="bottom" border-radius="10px 10px 0 0">
			<view class="get_account_popups">
				<!--  -->
				<view class="get_account_popups_title">
					<image src="../../static/bookkeeping/fireworks.png" mode="heightFix"></image>
					选择账户
				</view>
				<view class="account_list">
					<view class="account_item" 
						v-for="(item, index) of assetAccountData" 
						:key="index"
						:class="{'not_first_account': index != 0}"
						@click="selectAccountHandle(item)"
						>
						<view class="account_item_left">
							<view class="account_item_icon">
								<image :src="baseUrl2 + item.icon" mode="heightFix"></image>
							</view>
							<view class="account_item_name">
								{{ item.name }}
							</view>
						</view>
						<view class="account_item_balance">
							{{ item.balance }}
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		
		<!-- 插画 -->
		<view class="remember_smile" v-if="selectedTab == 2">
			<image src="../../static/bookkeeping/smile.png" mode="widthFix"></image>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onShow } from "@dcloudio/uni-app";

let baseUrl = uni.$baseUrl + "category$";

// 图片基础路径
let baseUrl2 = uni.$baseUrl;

// 账单参数
let billData = ref({
	userId: "",
	bookId: "", // 账本
	accountId: "", // 资产账户
	categoryId: "", // 账单分类（图标）,
	amount: "", // 金额
	type: "", // 收入：1 或 支出：2
	remark: "" // 备注
})

// 选择的分类
let selectedCategory = ref(0);

// 账本数据
let accountBookData = ref([]);
// 资产账户数据
let assetAcountData = ref([]);
let assetAcountOption = ref([]);
	
// 定义 Tab 栏数据
const tabs = ['支出', '收入', '转账'];
// 当前选中的 Tab
const selectedTab = ref(0)

// 收入和支付的图标数据
const incomeIcons = ref([]);
const expendIcons = ref([]);

// 转账参数
let transferValue = ref("0.00");

// 弹出层参数
let select_account = ref();
// 所有资金账户
let assetAccountData = ref([]);
// 当前点击的账户类型：转入还是转出
let popupsAccountType = ref("");
let expendAccount = ref({name: "转出账户"}); // 转出账户
let incomeAccount = ref({name: "转入账户"}); // 转入账户

onMounted(()=>{
	getAllPublicCategoryIcon();
	// 初始化账单参数
	initBillParams();
})

onShow(()=>{
	getUserAssetAccount();
	initBillParams();
})

// 弹出层选择账户处理器
function selectAccountHandle(item){
	// 判定当前选择的账户
	let res = false;
	if(popupsAccountType.value == "expend"){ // 转出类型
		res = diffAccountJudge(incomeAccount.value, item.name)
	}else{
		res = diffAccountJudge(expendAccount.value, item.name)
	}
	
	if(res && popupsAccountType.value == "expend"){
		expendAccount.value = item;
		select_account.value.close();
	}else if(res && popupsAccountType.value == "income"){
		incomeAccount.value = item;
		select_account.value.close();
	}
	
	console.log("转出账户：", expendAccount.value);
	console.log("转入账户：", incomeAccount.value);
	
}

// 账户对比函数：以防用户同时选择两个相同的账户（转入和转出账户不可一致）
function diffAccountJudge(diffObj, accountName){
	// 为空检测，如果没有选择，就不用比较
	if(diffObj.name == "转入账户" ||  diffObj.name == "转出账户"){
		return true;
	}
	
	if(diffObj.name == accountName){
		uni.$showT("转入和转出账户不能相同");
		return false;
	}
	
	return true;
}

// 获取用户所有账户，动态计算总资产
async function getUserAccount() {
    // 获取当前登录用户信息
    let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
    
    const res = await uni.$http.get(`/assetAccounts/getAllByUserId/${userInfo.id}`);
    
    // 资金账户为空
    if(res.data.code == 0){
        uni.$showT(res.data.msg);
        totalAsset.value = 0.00;
        return 0;
    }
    
    for (let item of res.data.data) {
		item.balance = item.balance.toFixed(2);
    }
    
    // 数据存储起来
    assetAccountData.value = res.data.data;
}

// 账单保存处理器
function addBillHandle(){
	// 检查是否是“转账”，是的话分发到转到函数处理
	if(selectedTab.value == 2){
		transferHandle();
		return 1;
	}
	
	// 补充默认参数
	let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
	billData.value.userId = userInfo.id;
	
	// 赋值订单类型: 根据当前选择的Tab项判定
	billData.value.type = selectedTab.value == 0? 2: 1;
	
	// 补充分类
	billData.value.categoryId = selectedCategory.value;
	
	// 判空
	for (let key in billData.value) {
		if(billData.value[key] == ""){
			uni.$showT("请填写完整后提交");
			return 1;
		}
	}
	execteAdd(billData.value);
	console.log("提交的对象参数：", billData.value);
	
}

// 执行添加
async function execteAdd(bill){
	const res = await uni.$http.post("/bills/addBill", bill);
	
	if(res.data.code == 0){
	    uni.$showT(res.data.msg);
	    return 0;
	}
	
	uni.showToast({
		title:"账单已保存"
	})
	
	// 置空表单数据
	for (let key in billData.value) {
		if(key != "categoryId"){
			billData.value[key] = "";
		}
	}
	
	// 更新资产账户余额
	getUserAssetAccount();
	
}

// 转账处理器
function transferHandle(){
	// 判断账户是否选择
	if(expendAccount.value.name == "转出账户"){
		uni.$showT("请选择转出账户");
		return 0;
	}else if(incomeAccount.value.name == "转入账户"){
		uni.$showT("请选择转入账户")
		return 0;
	}
	
	// 判断转出和转入金额是否已填写
	if(transferValue.value == "0.00" || transferValue.value <= 0){
		uni.$showT("请正确填写转账金额");
		return 0;
	}
	
	// 执行转账
	excuteTransfer();
}

async function excuteTransfer(){
	// 构造转账请求对象参数
	let paramsObj = {
		fromId: expendAccount.value.id,
		toId: incomeAccount.value.id,
		amount: parseFloat(transferValue.value)
	}
	
	console.log("转账参数：", paramsObj);
	
	const res = await uni.$http.post("/assetAccounts/transfer", paramsObj);
	
	if(res.data.code == 0){
		uni.$showT(res.data.msg);
		return 0;
	}
	
	uni.$showT("转账成功");
	
	// 置空操作
	expendAccount.value = {name: "转出账户"};
	incomeAccount.value = {name: "转入账户"};
	
	transferValue.value = "0.00";

	
}

// 显示账户的弹出框
function showSelectAccout(type){
	// 查询账户数据
	getUserAccount();
	// 显示弹出层
	select_account.value.open();
	
	// 标记当前选择的账户类型：转入还是转出
	popupsAccountType.value = type;
}

function initBillParams(){
	// 获取账本数据 和 当前选中的账本 默认赋值
	accountBookData.value = []; // 置空
	let selectAccountBookId = "";
	for (let item of uni.getStorageSync("accountBookData")) {
		accountBookData.value.push({value: item.id, text: item.name})
		
		if(item.name == uni.getStorageSync("selectedBook")){
			selectAccountBookId = item.id;
		}
	}
	
	// 设置选中的账本
	billData.value.bookId = selectAccountBookId;
}

// 获取用户资产账户
async function getUserAssetAccount(){
	// 获取当前登录用户信息
	let userInfo = JSON.parse(uni.getStorageSync("userInfo"));
	
	const res = await uni.$http.get(`/assetAccounts/getAllByUserId/${userInfo.id}`);
	
	// 资金账户为空
	if(res.data.code == 0){
	    uni.$showT(res.data.msg);
	    totalAsset.value = 0.00;
	    return 0;
	}
	assetAcountData.value = res.data.data;
	assetAcountOption.value = [];
	// 根据所有资金账户计算出总资产
	for (let assetAcount of assetAcountData.value) {
		assetAcount.balance = assetAcount.balance.toFixed(2);
		let textTemp = `${assetAcount.name} (余额:${assetAcount.balance})`;
		assetAcountOption.value.push({value: assetAcount.id, text: textTemp});
	}
	
}

// 获取所有公用的分类图标
async function getAllPublicCategoryIcon(){
	const res = await uni.$http.get("/categorys/public/icon");
	if(res.data.code == 0){
		uni.$showT(res.data.msg);
		return 0;
	}
	
	incomeIcons.value = res.data.data.income;
	expendIcons.value = res.data.data.expend;
	
	// 默认选择第一个分类
	selectedCategory.value = expendIcons.value[0].id;
}

// 切换 Tab 的方法
const selectTab = (index) => {
  selectedTab.value = index;
  if(index == 0){
	  selectedCategory.value = expendIcons.value[0].id;
  }else{
	  selectedCategory.value = incomeIcons.value[0].id;
  }
}	

// 切换选择分类
function switchCategory(item){
	selectedCategory.value = item.id;
}
	
</script>

<style lang="scss" scoped>
.tabs {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  background-color: #ffffff;
  width: 70%;
  margin: 0 auto;
  border-radius: 15rpx;
  position: relative; /* 为可能的滑动动画留有余地 */
}

.tab {
  padding: 15rpx 20rpx;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease; /* 添加过渡效果 */
  position: relative;
  z-index: 1;
  border-radius: 15px; /* 保持与active状态相同的圆角 */
}

.tab.active {
  color: white;
  background-color: #00aaff;
  /* 移除原来的border-radius继承 */
}

/* 如果需要更流畅的颜色过渡可以添加伪元素 */
.tab::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #009fee;
  border-radius: 15px;
  z-index: -1;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.tab.active::before {
  opacity: 1;
}

.content {
  // padding: 20px;
  margin-top: 5px;
  background-color: #fff;
}	

.content_view{
	box-sizing: border-box;
	display: flex;
	flex-wrap: wrap;
	padding: 20rpx 0px;
	// border: solid red 1px;
}

.expend_icon{
	width: 14%;
	padding: 20rpx;
	font-size: 13px;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	// border: solid red 1px;
}

.expend_icon_img image{
	height: 25px;
}

.expend_icon_text{
	margin-top: 6rpx;
	width: max-content
}

.bill_option{
	background-color: #fff;
	border-radius: 15rpx;
	// margin-top: 10rpx;
	padding: 30rpx 10px;
	border-top: solid #e8e8e8 1px;
}

.confirm_btn{
	width: 97vw;
	margin: 0 auto;
}

.selected_category{
	background-color: #ffc53c;
	border-radius: 15rpx;
}

.selected_category_t{
	color: #ffc53c;
	font-size: 15px;
	font-weight: 600;
}

// 转账样式开始
.transfer_view{
	padding: 40rpx 20rpx;
}

.expend_account, .income_account{
	display: flex;
	justify-content: space-between;
	padding: 30rpx;
	border: solid #d5d5d5 1px;
	border-radius: 15rpx;
	font-size: 14px;
}

.expend_account{
	position: relative;
	top: 15px;
}

.middle{
	position: absolute;
	font-size: 30px;
	left: 48%;
	color: red;
}

.middle2{
	position: absolute;
	font-size: 30px;
	left: 47%;
	color: #009fee;
}

.income_account{
	position: relative;
	bottom: 15px;
}

.expend_account_left, .income_account_left{
	display: flex;
	justify-content: center;
	align-items: center;
}

.expend_account_icon image{
	height: 25px;
}

.income_account_icon image{
	height: 25px;
}

.right_inpt{
	border-bottom: solid #919191 1px;
	width: 110px;
	text-align: center;
	font-weight: 600;
}

.expend_account_name, .income_account_name{
	position: relative;
	bottom: 2px;
	left: 5px;
	font-weight: 700;
}

.transfer_icon{
	position: relative;
	// border: solid red 1px;
	display: flex;
	justify-content: center;
}

.transfer_icon image{
	height: 50px;
}

.remember_smile{
	background-color: #fff;
	display: flex;
	justify-content: center;
	padding: 20px 0px;
}

.get_account_popups{
	background-color: #e6e6e6;
	padding: 30rpx 20rpx;
	font-size: 14px;
}

.account_list{
	background-color: #fff;
	border-radius: 15rpx;
	padding: 20rpx;
	margin-top: 10px;
}

.get_account_popups_title{
	text-align: center;	
	background-color: #fff;
	padding: 10rpx 0px;
	border-radius: 15rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.get_account_popups_title image{
	height: 30px;
}

.account_item{
	display: flex;
	justify-content: space-between;
	align-items: center;
	// border: solid red 1px;
	padding: 20rpx 20rpx;
	// margin-top: 10rpx;
}

.account_item_left{
	display: flex;
	align-items: center;
}

.account_item_icon{
	position: relative;
	top: 2px;
}

.account_item_name{
	position: relative;
	left: 8px;
}

.account_item_icon image{
	height: 28px;
}

.account_item_balance{
	font-weight: 600;
	font-size: 15px;
}

.not_first_account{
	border-top: solid 1px #e3e3e3;
}

.account_balance{
	font-size: 12px;
	color: #565656;
}
	
</style>
